from flask import Blueprint, request
from flask_cors import CORS
from services.ithome import (
    get_daily_ithome_hotspot_from_db,
    get_weekly_ithome_hotspot_from_db,
    get_monthly_ithome_hotspot_from_db,
    get_latest_ithome_hotspot_from_db,
    get_hot_ithome_hotspot_from_db,
    get_latest_ithome_hotspot_from_db_page,
)

from blueprints.utils import response_error, response_success, is_page_out_of_bounds

ithome_bp = Blueprint("ithome", __name__, url_prefix="/ithome")

CORS(
    ithome_bp, resources={r"/*": {"origins": "http://localhost:5173", "methods": ["GET"], "supports_credentials": True}}
)


@ithome_bp.route("/daily", methods=["GET"])
def get_ithome_hotspot_day():
    """
    获取IT之家日榜数据

    测试地址：http://127.0.0.1:5000/ithome/daily
    """
    # 调用服务层函数获取数据
    result = get_daily_ithome_hotspot_from_db()
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)


@ithome_bp.route("/weekly", methods=["GET"])
def get_ithome_hotspot_week():
    """
    获取IT之家周榜数据

    测试地址：http://127.0.0.1:5000/ithome/weekly
    """
    # 调用服务层函数获取数据
    result = get_weekly_ithome_hotspot_from_db()
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)


@ithome_bp.route("/monthly", methods=["GET"])
def get_ithome_hotspot_month():
    """
    获取IT之家月榜数据

    测试地址：http://127.0.0.1:5000/ithome/monthly
    """
    # 调用服务层函数获取数据
    result = get_monthly_ithome_hotspot_from_db()
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)


@ithome_bp.route("/latest", methods=["GET"])
def get_ithome_hotspot_latest():
    """
    获取IT之家月最新数据

    测试地址：http://127.0.0.1:5000/ithome/latest
    """
    # 调用服务层函数获取数据
    result = get_latest_ithome_hotspot_from_db()
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)


@ithome_bp.route("/hot", methods=["GET"])
def get_ithome_hotspot_hot():
    """
    获取IT之家热评榜数据

    测试地址：http://127.0.0.1:5000/ithome/hot
    """
    # 调用服务层函数获取数据
    result = get_hot_ithome_hotspot_from_db()
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)


@ithome_bp.route("/latest/page", methods=["GET"])
def get_ithome_hotspot_page():
    """
    获取IT之家最新数据

    测试地址：http://127.0.0.1:5000/ithome/latest/page?page=1&page_size=10
    """
    # 获取请求参数
    page = int(request.args.get("page", 1))
    page_size = int(request.args.get("page_size", 10))
    if is_page_out_of_bounds(page, page_size):
        return response_error("page 或 page_size 不合理")

    # 调用服务层函数获取数据
    result = get_latest_ithome_hotspot_from_db_page(page, page_size)
    hotspots = [hotspot.to_dict() for hotspot in result["items"]]
    result["items"] = hotspots
    return response_success(result)